<template>    
    <el-dialog
      :title="title"
      :visible.sync="visible"
      width="800px" 
      :before-close="handleClose"
      class="announcement-edit-dialog"
    >
      <el-form :model="form" :rules="rules" ref="form" label-width="100px" label-position="right">
        <el-form-item label="车位号" prop="parkingNumber">
          <el-input style="width: 500px" v-model="form.parkingNumber" placeholder="请输入车位号" maxlength="3"></el-input>
        </el-form-item>

        <el-form-item label="位置" prop="location">
          <el-input style="width: 500px" v-model="form.location" placeholder="请输入位置"></el-input>
        </el-form-item>
        
        <el-form-item label="车位状态" prop="status">
            <el-radio-group v-model="form.status">
                <el-radio :label="0">未出售</el-radio>
                <el-radio :label="1">已出售</el-radio>
            </el-radio-group>
        </el-form-item>

        <el-form-item v-if="form.status === 1" label="车位业主" prop="userId">
          <el-select v-model="form.userId" filterable placeholder="请选择业主">
              <el-option
                v-for="item in updateUserOptins"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
          </el-select>
      </el-form-item>
      </el-form>
      
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="submitForm('form')">确 定</el-button>
      </span>
    </el-dialog>
    
  </template>
  
  <script>
import { cloneDeep } from 'lodash';
import api from '@/api';
 import { mapState,mapMutations } from "vuex"


  export default {  
    computed:{
      ...mapState("login",["user"])
    },
    props: {
      visible: {
        type: Boolean,
        default: false
      },
      formData: {
        type: Object,
        default: () => ({})
      },
      title:{
        type: String,
        default: '新增车位'
      },
      userOptions:{
        type: Array,
        default: () => []
      }
    },
    data() {
      return {
        form: {
          id:'',
          userId:'',
          parkingNumber: '',
          location:'',
          status: 0
        },
        updateUserOptins: this.userOptions,
        rules: {
          parkingNumber: [
            { required: true, message: '请输入车位号', trigger: 'blur' },
            { min: 3, max: 3, message: '用户名长度必须在 3 到 20 个字符之间', trigger: 'blur' },
            {
              pattern: /^\d{3}$/, // 正则表达式，匹配 3 位数字
              message: '车位号必须是 3 位数字',
              trigger: 'blur',
            },
          ],
          location: [
            { required: true, message: '请输入位置', trigger: 'blur' },
            { min: 2, max: 4, message: '位置长度必须在 2 到 4个字符之间', trigger: 'blur' },
            {
              pattern: /^[a-zA-Z\u4e00-\u9fa5]+$/, // 正则表达式，匹配英文和中文
              message: '位置必须是中文或者英文',
              trigger: 'blur',
            }
          ],
          userId: [
            { required: () => this.form.status === 1, message: '请选择车位业主', trigger: 'blur' }
          ]
        },
      }
    },
    methods: {
      submitForm(form) {
        this.$refs[form].validate((valid) => {
          if (valid) {
            api.saveOrUpdatePark(this.form).then(res =>{
              if(res.type === 'error'){
                this.$message.error(res.message)
              }else if(res.data.code === 200){
                  location.reload();
                  this.$message({
                    message: '操作成功',
                    type: 'success'
                  })
              }else{
                this.$message.error(res.data.message)
              }
            })
          } else {
            this.$message.error('请完善表单信息');
            return false;
          }
        });
      },

      //设置日期格式
      formatDate(date) {
          const year = date.getFullYear();
          const month = String(date.getMonth() + 1).padStart(2, '0');
          const day = String(date.getDate()).padStart(2, '0');
          return `${year}-${month}-${day}`;
      },

      handleClose() {
        // 手动清空表单
        this.form = {
          id:'',
          userId:'',
          parkingNumber: '',
          location:'',
          status: 0
        };
        // 重置表单验证状态
        this.$refs['form'].resetFields();
        this.$emit('updateFormData', {});
        this.$emit('update:visible', false);
        this.$emit('update:title', '新增车位');
      },
    },
    watch: {
        // 监听 formData 的变化
        formData: {
            handler(newVal) {
                if (newVal && Object.keys(newVal).length > 0) {
                    // 深拷贝 formData 并赋值给 ruleForm
                    this.form = cloneDeep(newVal);
                }
            },
            immediate: true, // 立即执行一次
            deep: true, // 深度监听
        },
        // 监听 userOptions 的变化
        userOptions: {
          handler(newVal) {
            if (newVal && newVal.length > 0) {
              // 更新 updateUserOptins
              this.updateUserOptins = cloneDeep(newVal);
            }
          },
          immediate: true, // 立即执行一次
          deep: true, // 深度监听
        },
    },
  }
  </script>
  
  <style scoped>

  .announcement-edit-dialog >>> .el-dialog__body {
    padding: 20px 30px;
  }
  
  .editor-wrapper {
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    overflow: hidden;
  }
  
  .editor-toolbar {
    border-bottom: 1px solid #dcdfe6;
    background-color: #f5f7fa;
  }
  
  .editor-content {
    min-height: 300px;
    max-height: 500px;
    overflow-y: auto;
  }
  
  .editor-form-item >>> .el-form-item__content {
    line-height: normal;
  }
  
  .line {
    line-height: 36px;
    color: #909399;
  }
  </style>